package sharing

import groovy.sql.Sql
import net.sf.json.JSONArray

class UserWaittingTaskService {

    static transactional = true

    def dataSource
    def barcodeService
    def utilsService
    def utils2Service
    /**
     * 待办任务查询相关，拼接分页查询的头部SQL内容
     * @return
     */
    private StringBuilder getPageStartSql() {
        def pageStartSql = new StringBuilder();
        pageStartSql.append "select tmp3.*, sm.realname as waitUser, d.name as waitDpt, "
        pageStartSql.append " sm2.realname as create_name, d2.name as create_dpt_name "
//        pageStartSql.append " cd.top_flowId "    //2013-10-02      待办任务添加  top_flowId 为了几点待办任务时能据topFlowId和当前操作人所在当前进行筛选(可查看本单位和下级单位的)历史环节
        pageStartSql.append "  from ( "
        pageStartSql.append " select * from ("
        pageStartSql.append " select tmp.*, rownum rm from ( "

        return pageStartSql
    }

    /**
     * 拼接查询条件
     * @param params 用于接收由界面等外部方式传入参数
     * @param fromSqlStrSb 拼接的部分SQL，参照getFromSqlStrSb()
     * @param paramList 查询条件的记录列表
     * @return
     */
    private appendQuery(params, StringBuilder fromSqlStrSb, List paramList) {

        // 拼接查询条件
        def content

        // 标题
        if (params.title) {
            fromSqlStrSb.append " and title like ? "
            content = '%' + params.title + '%'
            paramList << content
        }

        // 环节名称
        if (params.htNameZh) {
            fromSqlStrSb.append " and ht_name_zh like ? "
            content = '%' + params.htNameZh + '%'
            paramList << content
        }

        // 流程模板名
        if (params.templateName) {
            fromSqlStrSb.append " and key_ = ? "
            paramList << params.templateName.toString().trim()
        }

        // 流程发起时间
        if (params.startTime) {
            fromSqlStrSb.append " and creater_time >= to_date(?, 'yyyy-mm-dd hh24:mi:ss') "
            content = params.startTime.substring(0, 10) + ' 00:00:00'
            paramList << content
        }
        if (params.endTime) {
            fromSqlStrSb.append " and creater_time <= to_date(?, 'yyyy-mm-dd hh24:mi:ss') "
            content = params.endTime.substring(0, 10) + ' 23:59:59'
            paramList << content
        }

        // 任务到达时间 uwt.create_time
        if (params.taskCreateStart) {
            fromSqlStrSb.append " and create_time >= to_date(?, 'yyyy-mm-dd hh24:mi:ss') "
            content = params.taskCreateStart
            paramList << content
        }
        if (params.taskCreateEnd) {
            fromSqlStrSb.append " and create_time <= to_date(?, 'yyyy-mm-dd hh24:mi:ss') "
            content = params.taskCreateEnd
            paramList << content
        }

        if (params.fqr) {
            fromSqlStrSb.append " and fqr like ? "
            content = "%${params.fqr}%"
            paramList << content.toString()
        }

        if (params.fqbm) {
            fromSqlStrSb.append " and fqbm like ? "
            content = "%${params.fqbm}%"
            paramList << content.toString()
        }
        if (params.taskId) {// App 分页使用
            fromSqlStrSb.append " and task_Id< ${params.taskId}"
        }
        if (params.Apps) {// App 支持 的流程,并且只是处于发起环节  用于编辑发起上传图片
            fromSqlStrSb.append " and key_ in (select key from  Act_Model am,Act_Solution ast  where  ast.act_Model_id=am.id  and ast.sy_App=1 )  and  ht_name in (select task_Id  from Act_Solution_Mx  where is_Start_Task=1)"
        }
        if (params.lcName){
            fromSqlStrSb.append " and key_= '${params.lcName}'"
        }
    }

    /**
     * 拼接查询条件
     * @param fromSqlStrSb 拼接的部分SQL，参照getFromSqlStrSb()
     * @param paramList 查询条件的记录列表
     * @return
     */
    private appendOwner(StringBuilder fromSqlStrSb, List paramList, String username) {
        // 只查询指定人员的待办任务
        fromSqlStrSb.append " and assignee = ? "
        paramList << username
    }

    /**
     * 拼接分页查询待办任务的结束部分SQL
     * @return
     */
    private getPageEndSql(params) {
        def pageEndSql = new StringBuilder();
        pageEndSql.append " ) tmp "
        // 编号
        if (params.commtaskCode) {
            pageEndSql.append " where  tmp.commtask_code like '%${params.commtaskCode}%' "
        }
        pageEndSql.append " ) tmp2 "
        pageEndSql.append " where tmp2.rm > ? "
        pageEndSql.append " and tmp2.rm <= ? "

        pageEndSql.append " ) tmp3 "
        pageEndSql.append ' left join staff_member  sm on sm.username = tmp3.assignee '
        pageEndSql.append 'left join staff_member  sm2 on sm2.id = tmp3.creater_id '
        pageEndSql.append ' left join department  d on d.id = sm.department_id '
        pageEndSql.append ' left join department  d2 on d2.id = tmp3.creater_dpt_id'
        if (params.Apps)   pageEndSql.append " order by task_Id desc "
        else   pageEndSql.append " order by tmp3.create_time desc "

        return pageEndSql
    }

    private setPageParams(params, List paramList) {
        paramList.add(getIntValue(params.offset))

        if (!params.max) {
            params.max = 15
        }
        def maxIdx = getIntValue(params.offset) + (params.max ? Integer.valueOf(params.max) : 15)
        paramList.add(maxIdx)
    }

    def getTaskLstJson(params, username) {
        // 记录查询参数
        List paramList = new ArrayList()

        // 分页查询SQL头部分
        def pageStartSql = getPageStartSql()

        // 详情字段查询部分
        def selDetailSql =new StringBuilder()
        selDetailSql.append("select  *  ")

        // 查询表及条件拼接部分
        def sqlStrSb =new StringBuilder()
        sqlStrSb.append("from sydb where 1=1 ")

        appendQuery(params, sqlStrSb, paramList)

        // 只查询当前登录人员的待办任务
        appendOwner(sqlStrSb, paramList, username)
        if(!params.Apps&&params.taskId){
            sqlStrSb.append " and task_id = ? "
            paramList << params.taskId
        }
        // 任务数量查询
        def selCntSql = "select count(1) " + sqlStrSb
        log.debug "[CommonTasksLst] 待办任务数量查询 selCntSql = [" + selCntSql + "] params=[" + paramList + "]"
        def sql = new Sql(dataSource);
        def cnt = sql.rows(selCntSql.toString(), paramList).get(0)[0]
        log.debug "[CommonTasksLst] 待办任务数量查询  cnt=[" + cnt + "]"

//        sqlStrSb.append " order by uwt.create_time desc"

        // 分页查询尾部分SQL
        def pageEndSql = getPageEndSql(params)

        // 设置分页查询参数 原来是100０　
        if (!params.max) params.max = 15
        setPageParams(params, paramList)
        def sqlStr = pageStartSql.append(selDetailSql).append(sqlStrSb).append(pageEndSql)
        log.debug "[CommonTasksLst] 待办任务查询 sqlStr = [" + sqlStr + "] params=[" + paramList + "]"
        List rs = sql.rows(sqlStr.toString(), paramList)
        def relist=[]
        rs.each {
            def temmap=[:]
            temmap.putAll(it as Map)
            relist<<temmap
        }
        buildJson(relist, cnt)

    }

    def usertaskcount (){
        //  改动后任务查询包括:查询人参与过的流程(已经操作过流程某环节)+代办任务
        def sql = new Sql(dataSource)
        def sqlStr = """ --- 我发起的流程
            SELECT   count(1)
from  fqlc  lc LEFT OUTER JOIN WINDOW_CONFIG wg on LC.HT_NAME=wg.STEP_NAME
 where 1=1 and lc.status=1
                """
        def user = utilsService.currentUser
        sqlStr += " and cyusername ='${user.username}'"
        sqlStr += "  order by date_created desc"
        log.debug(sqlStr)
        def cnt = sql.rows(sqlStr.toString()).get(0)[0]
        return cnt
    }


    def buildJson(rs, rscount) {
//        def xmList=utils2Service.configList()
        def list=[]
        rs.each{
//            def xm=xmList.find{itt->itt.xmmc==it.XMMC}
            def temmap=[
                    id: it.TASK_ID,        // uwt.task_id 任务ID
                    taskId: it.TASK_ID,           // uwt.task_id 任务ID
                    piid: it.PIID,             // 流程实例号
                    htNameZh: it.HT_NAME_ZH,         // 环节中文名
                    htName: it.HT_NAME  ,         // 环节名称标识
                    assignee: it?.ASSIGNEE,         // 待办人
                    createTime: it.CREATE_TIME,       // 任务创建时间
                    title: it.TITLE,            // 任务标题
                    createrId: it.CREATER_ID,       // 流程创建人ID
                    createrDptId: it.CREATER_DPT_ID,    // 流程创建人部门ID
                    createrTime: it.CREATE_TIME,      // 流程发起时间
                    templateName: it.KEY_,    // 流程模板标识
                    flowId: it.FLOW_ID,          // 流程流水号
                    templateNameZh: it.NAME_?:it.PROCESSNAME, // 流程模板中文名
                    startStepName: it.START_STEP_NAME,   // 工单详情Form名称
                    hisFormNameURL: it.HIS_FORM_NAMEURL,  // 历史记录列表查询URL
                    hisDataURL: it.HIS_DATAURL,      // 历史环节数据记录获取URL
                    curDataURL: it.CUR_DATAURL,      // 当前处理环节数据记录获取URL
                    startStepURL: it.START_STEPURL,    // 工单发起环节数据获取URL
                    formName: it.TACHE_FORM_NAME,       // 当前环节Form名称
                    isStartTask: it.IS_START_TASK,    // 是否发起环节
                    batchUrl: it.BATCH_URL,    // 是否发起环节
                    saveURL: it.SAVEURL,    // 是否发起环节
                    fqr: it.FQR,    //  发起人姓名
                    fqbm: it.FQBM,    //  发起部门
                    commtaskCode: it.COMMTASK_CODE,       // 单据编号
                    rm: it.RM,             // 行号
                    waitUser: it.WAITUSER,       // 待办人姓名
                    waitDpt: it.WAITDPT,        // 待办人部门名
                    createrName: it.CREATE_NAME,    // 本环节创建人姓名
                    createDtp: it.CREATE_DPT_NAME,     // 本环节创建部门名
                    xmmc: it.XMMC,
                    picurl: it.PICURL,
//                    url:xm?.address,// http://localhost:8010/jcjt
                    endTime:it.ENDTIME,// 流程结束时间
                    djtm: barcodeService.generalBarcodeString(it.PIID as long)//单据条码
            ]
            temmap.put("jsonStr", JSONArray.fromObject(temmap).toString() )
            list<<temmap
        }
        def result=[success:true,total:rscount,gridroot:list]

        result
    }

    private getIntValue(def offset) {
        return offset ? Integer.parseInt(offset) : 0
    }

    /**
     * 本方法主要用于首页上的任务提醒功能。
     * @param params 查询参数，主要用于查询时间段内新到达的任务
     *   需要的参数如下：
     *   1、taskCreateStart ： 任务到达时间，查询的起始时间(24H形式)。字符串，格式：yyyy-MM-dd HH:mm:ss
     *   2、taskCreateEnd   ： 任务到达时间，查询的结束时间(24H形式)。字符串，格式：yyyy-MM-dd HH:mm:ss
     *
     *   参数使用方法：
     *   params.taskCreateStart = '2013-04-25 09:26:00'
     *   params.taskCreateEnd = '2013-04-25 21:26:59'
     *
     * @return Map形式的结果，包含内容如下：
     *   [
     *     totle: 29,
     *     currentCnt: 2,
     *     taskIds: [1024, 1023, 1022]
     *   ]
     *
     *   返回结果各字段意义：
     *   1、totle ：当前用户下的总待办任务数量
     *   2、currentCnt : 在当前查询时间段内，新到达的任务数量。取决于参数taskCreateStart和taskCreateEnd
     *   3、taskIds ：List集合，记录当前时间段内新到达各任务的TaskID
     */
    def getRemindResult(params, username) {

        // 影响结果
        def result = [:]

        // 1. 查询总的待办任务数量
        List paramList = new ArrayList()

        def sqlStrSb = getFromSqlStrSb()
        // 只查询当前登录人员的待办任务
        appendOwner(sqlStrSb, paramList, username)

        def selCntSql = "select count(1) " + sqlStrSb

        def sql = new Sql(dataSource);
        def cnt = sql.rows(selCntSql.toString(), paramList).get(0)[0]
        log.debug "[getRemindResult] 待办任务数量查询  cnt=[" + cnt + "]"

        result.totle = cnt

        // 2. 查询当前指定时间段内的待办任务数量
        List currParamList = new ArrayList()
        def currTaskSqlStrSb = getFromSqlStrSb()
        appendQuery(params, currTaskSqlStrSb, currParamList)
        appendOwner(currTaskSqlStrSb, currParamList, username)

        def selCurrCntSql = "select count(1) " + currTaskSqlStrSb
        def currSql = new Sql(dataSource);
        def currCnt = currSql.rows(selCurrCntSql.toString(), currParamList).get(0)[0]
        log.debug "[getRemindResult] 当前时间段[${params?.taskCreateStart} ~ ${params?.taskCreateEnd}] currCnt=[" + currCnt + "]"
        result.currentCnt = currCnt

        // 3. 查询当前指定时间段内的待办任务信息
        def taskInfoSqlSb = new StringBuilder()
        taskInfoSqlSb.append " select tmp2.task_id, tmp2.piid, tmp2.create_time, tmp2.rm from ( "
        taskInfoSqlSb.append " select tmp.*, rownum rm from ( "

        taskInfoSqlSb.append getSelDetailSql()
        taskInfoSqlSb.append currTaskSqlStrSb

        taskInfoSqlSb.append " order by uwt.create_time desc"

        taskInfoSqlSb.append " ) tmp "
        taskInfoSqlSb.append " ) tmp2 "
        taskInfoSqlSb.append " where tmp2.rm > ? "
        taskInfoSqlSb.append "   and tmp2.rm <= ? "

        // 设置分页查询参数
        setPageParams(params, currParamList)

        log.debug "[getRemindResult] 当前时间段[${params?.taskCreateStart} ~ ${params?.taskCreateEnd}]待办任务查询  taskInfoSqlSb = [" + taskInfoSqlSb + "] params=[" + currParamList + "]"

        List rs = sql.rows(taskInfoSqlSb.toString(), currParamList)
        def taskIdsLst = []
        rs?.each {
            taskIdsLst << it[0]  // 待办任务ID
        }

        result.taskIds = taskIdsLst

        result
    }

    def disposeBarcode(params) {
        def barCode = params.barCode

    }

}
